package com.oss.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oss.PMF;
import com.oss.model.Link;
import com.oss.model.Project;
import com.oss.model.Site;
import com.oss.model.Topic;

/**
 * @author xueqiang.mi
 * @date 2010-2-8
 */
public class LinkService extends BaseService {

	/**
	 * 添加Link，同时抽取该链接来源，存入Site
	 */
	public void add(Link obj) {
		PersistenceManager pm = PMF.get();
		try {
			if (!isExist(obj.getName())) {
				// 添加Link
				pm.makePersistent(obj);
				// 添加Site
				String url = getSiteFromUrl(obj.getUrl());
				Site site = new Site(getDefaultSiteName(url), url);
				new SiteService().add(site);

				// 统计链接数量
				if (!obj.getPrj().equals("notSet")) {
					Project prj = pm.getObjectById(Project.class, obj.getPrj());
					if (prj.getLinkQuantity() == null) {
						prj.setLinkQuantity(0L);
					}
					prj.add1Link();
				}
				if (!obj.getTopic().equals("notSet")) {
					Topic topic = pm.getObjectById(Topic.class, obj.getTopic());
					if (topic.getLinkQuantity() == null) {
						topic.setLinkQuantity(0L);
					}
					topic.add1Link();
				}
			}
		} finally {
			pm.close();
		}
	}

	/**
	 * 统计某Project的Link数量
	 */
	@Deprecated
	public Long countLnksByPrj(String role, String prj) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			// hidden disabled projects for users and anonymous
			if (role.equals("admin")) {
				query.setFilter("prj == :prj");
			} else {
				query.setFilter("prj ==:prj && enabled == true");
			}
			query.setResult("sum(id)");
			Long number = (Long) query.execute(prj);
			return number;
		} finally {
			pm.close();
		}
	}

	public void delete(Long id) {
		PersistenceManager pm = PMF.get();
		try {
			Link link = pm.getObjectById(Link.class, id);
			// 相应的项目的链接数量增加减
			if (!link.getPrj().equals("notSet") && !link.getPrj().equals("unSet")) {
				Project prj = pm.getObjectById(Project.class, link.getPrj());
				if (prj.getLinkQuantity() == null) {
					prj.setLinkQuantity(0L);
				} else {
					prj.delete1Link();
				}
			}
			// 删除链接
			pm.deletePersistent(link);
		} finally {
			pm.close();
		}
	}

	public Link get(Long id) {
		PersistenceManager pm = PMF.get();
		try {
			Link link = pm.getObjectById(Link.class, id);
			return link;
		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Link> getLatestLnks(long pageIndex, long pageSize) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			query.setFilter("enabled == true");
			query.setOrdering("createdDate desc");
			query.setRange((pageIndex - 1) * pageSize, pageIndex * pageSize);
			Collection<Link> c = pm.detachCopyAll((Collection<Link>) query.execute());
			return new ArrayList<Link>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Link> getLnksByPrj(String role, String prj, long pageIndex, long pageSize) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			// hidden disabled projects for users and anonymous
			if (role.equals("admin")) {
				query.setFilter("prj == :prj");
			} else {
				query.setFilter("prj ==:prj && enabled == true");
			}
			query.setOrdering("createdDate desc");
			query.setRange((pageIndex - 1) * pageSize, pageIndex * pageSize);
			Collection<Link> c = pm.detachCopyAll((Collection<Link>) query.execute(prj));
			return new ArrayList<Link>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Link> getLnksByTopic(String topic, long pageIndex, long pageSize) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			query.setFilter("topic == :topic && enabled == true");
			query.setOrdering("createdDate desc");
			query.setRange((pageIndex - 1) * pageSize, pageIndex * pageSize);
			Collection<Link> c = pm.detachCopyAll((Collection<Link>) query.execute(topic));
			return new ArrayList<Link>(c);
		} finally {
			pm.close();
		}
	}

	public List<Link> getNews(long pageIndex, long pageSize) {
		return getLnksByTopic("news", pageIndex, pageSize);
	}

	/**
	 * 获得taskNumberPerTime个未进行归类的Link
	 * 
	 * @param taskNumberPerTime
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Link> getUnSetLink(Integer taskNumberPerTime) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			query.setFilter("prj == 'unSet'");
			query.setRange(0, taskNumberPerTime);
			Collection<Link> c = pm.detachCopyAll((Collection<Link>) query.execute());
			return new ArrayList<Link>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	private boolean isExist(String name) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Link.class);
			query.setFilter("name == :name");
			Collection<Link> c = (Collection<Link>) query.execute(name);
			if (c == null || c.isEmpty()) {
				return false;
			}
			return true;
		} finally {
			pm.close();
		}
	}

	public void save(Link lnk) {
		PersistenceManager pm = PMF.get();
		try {
			pm.makePersistent(lnk);
		} finally {
			pm.close();
		}
	}

	public void update(Link lnk) {
		PersistenceManager pm = PMF.get();
		try {
			Link link = pm.getObjectById(Link.class, lnk.getId());
			link.setName(lnk.getName());
			link.setDescription(lnk.getDescription());
			link.setUrl(lnk.getUrl());
			link.setTag(lnk.getTag());
			link.setPrj(lnk.getPrj());
		} finally {
			pm.close();
		}
	}
}
